package com.tinyproxy.common;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.util.FileSize;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * 采用代码方式配置日志输出
 *
 * @author catii
 */
public class LogbackCfg {

    private static final String PATTERN = "[%d{MM-dd HH:mm:ss} %level]%logger{35} %msg %n";

    /**
     * 构造Logger
     * 设置路径
     * 设置滚动(只能通过大小滚动，日期貌似有bug)
     */
    public static void start() {
        LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
        ctx.stop();

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setPattern(PATTERN);
        encoder.setCharset(StandardCharsets.UTF_8);
        encoder.setContext(ctx);
        encoder.start();

        RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>();
        fileAppender.setContext(ctx);
        fileAppender.setAppend(true);
        fileAppender.setName("file");
        fileAppender.setFile(Kits.executablePrefix() + ".log");
        fileAppender.setEncoder(encoder);

        SizeBasedTriggeringPolicy<ILoggingEvent> stp = new SizeBasedTriggeringPolicy<>();
        stp.setMaxFileSize(FileSize.valueOf("1mb"));
        stp.setContext(ctx);
        stp.start();

        TinyRollingPolicy tinyRolling = new TinyRollingPolicy(Kits.executablePrefix() + "_%d.log");
        tinyRolling.setMinIndex(1);
        tinyRolling.setMaxIndex(2);
        tinyRolling.setParent(fileAppender);
        tinyRolling.setContext(ctx);
        tinyRolling.start();
        fileAppender.setTriggeringPolicy(stp);
        fileAppender.setRollingPolicy(tinyRolling);
        fileAppender.start();

        ConsoleAppender<ILoggingEvent> stdAppender = new ConsoleAppender<>();
        stdAppender.setContext(ctx);
        stdAppender.setEncoder(encoder);
        stdAppender.start();

        Logger rootLogger = ctx.getLogger("ROOT");
        rootLogger.setLevel(Level.INFO);
        rootLogger.addAppender(fileAppender);
        rootLogger.addAppender(stdAppender);

        ctx.start();
    }

}
